package com.imufe.chemicalenterprisedangerwarning.aspect;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 切面组件
 * 控制器层日志
 *
 * @author BaiBan
 * @since 2022/8/3
 */

@Component
@Aspect
@Slf4j
public class ControllerLogAspect {

    @Pointcut("execution(* com.imufe.chemicalenterprisedangerwarning.controller.*.*(..))")
    public void pointcut() {

    }

    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();

        // 只记录post请求
//        if ("GET".equals(request.getMethod())) return;

        // String url = String.valueOf(request.getRequestURL());
        String ip = request.getRemoteAddr();
        String path = String.format("%s.%s", joinPoint.getSignature().getDeclaringType().getSimpleName(), joinPoint.getSignature().getName());

        log.info(String.format("用户 [%s], 访问了 %s 方法", ip, path));

        // 获取参数, 只取自定义的参数, 自带的HttpServletRequest, HttpServletResponse不管
        if (joinPoint.getArgs().length > 0) {
            for (Object o : joinPoint.getArgs()) {
                if (Objects.isNull(o) || o instanceof MultipartFile || o instanceof MultipartFile[] || o instanceof HttpServletRequest || o instanceof HttpServletResponse) {
                    continue;
                }
                log.info("请求参数 : " + JSONObject.toJSONString(o));
            }
        }
    }
}
